package net.dl.ss.web;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.dl.ss.dao.AdjudicatorDao;
import net.dl.ss.dao.CoupleDao;
import net.dl.ss.dao.RoundDao;
import net.dl.ss.domain.Adjudicator;
import net.dl.ss.domain.Category;
import net.dl.ss.domain.Couple;
import net.dl.ss.domain.Round;
import net.dl.ss.service.ContextManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author yakovlev.yuriy@gmail.com
 * @since 12.8.2008
 */
@Controller
public class RoundsController extends BaseController {
	protected final Log logger = LogFactory.getLog(getClass());
	private final RoundDao roundDao;
	
	@Autowired
	public RoundsController(RoundDao roundDao) {
		this.roundDao = roundDao;
	}
	
	@RequestMapping("/roundsList.htm")
	protected void roundsListHandler(HttpServletRequest request, HttpServletResponse response) {
		try {
			ServletOutputStream  os = response.getOutputStream();
			modifyResponseHeader(response, "text/xml");
			
		    os.println("<rounds>");
		    Long categoryId = ContextManager.getCurrentCategory(request);
		    if(categoryId!=null) {
		    	List<Round> rounds = this.roundDao.findByCategoryId(categoryId);
		    	for(Round round : rounds) {
		    		os.print(round.toXML());
		    	}
		    }
		    os.println("</rounds>");
	
			os.close();
		} catch (IOException e) {
			logger.error(e.getMessage());
		} 
	}
	
	@RequestMapping("/roundUpdate.htm")
	public void roundUpdateHandler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletOutputStream  os = response.getOutputStream();
		modifyResponseHeader(response, "text/plain");
		
		Long categoryId = ContextManager.getCurrentCategory(request);
	    if(categoryId!=null) {
			Round round = new Round();
			round.setCategoryId(categoryId);
			round.setName(request.getParameter("name"));
			String time = request.getParameter("time");
			if(time!=null && !"".equals(time)) {
				try {
					SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mm:ss");
					java.util.Date dt = sdf.parse(time);
					java.sql.Timestamp timestamp = new java.sql.Timestamp(dt.getTime());
					round.setTime(timestamp);
				} catch(ParseException ex) {
					logger.error(ex.getMessage());
				}
			}
			round.setRank(getParameter(request, "rank", Integer.class));
			round.setCouplesNumber(getParameter(request, "couplesNumber", Integer.class));
			round.setMinSuccCouples(getParameter(request, "minSuccCouples", Integer.class));
			round.setMaxSuccCouples(getParameter(request, "maxSuccCouples", Integer.class));
			round.setMode(getParameter(request, "mode", Integer.class));
			round.setPassingScore(getParameter(request, "passingScore", Integer.class));
			round.setSetsNumber(getParameter(request, "setsNumber", Integer.class));
			round.setFinalDanceTime(request.getParameter("finalDanceTime"));
			round.setReDance(getParameter(request, "reDance", Integer.class));
			try {
				String id = request.getParameter("id");
				if(id!=null && !"".equals(id)) {
					round.setId(Long.parseLong(id));
					this.roundDao.updateEntity(round);
				} else {
					this.roundDao.saveEntity(round);
				}
				os.print("{success:true}");
			} catch(Exception ex) {
				logger.error(ex.getMessage());
			}
	    } else {
	    	os.print("{success:false}");
	    }
	    os.close();
	}
	
	@RequestMapping("/roundDelete.htm")
	public void coupleDeleteHandler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletOutputStream  os = response.getOutputStream();
		modifyResponseHeader(response, "text/plain");
		try {
			String id = request.getParameter("id");
			if(id!=null && !"".equals(id)) {
				this.roundDao.deleteEntityById(Long.parseLong(id));
				os.print("{success:true}");
			} else {
				os.print("{success:false}");
			}
		} catch(Exception ex) {
			logger.error(ex.getMessage());
		}
		os.close();
	}

}
